<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\model\Sms;
use App\Http\model\Curdpost;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\User;
use Illuminate\Support\Facades\Cache;
use App\Wechat\Autoloader;

class PayController extends BaseController
{
    /**
     * 充值信息接口
     * by 吉星
     */
    // 生成微信充值预订单
    public function WeiXinAppPay(Request $request){
        ini_set('date.timezone','Asia/Shanghai');  
        require_once "../app/Wechat/Autoloader.php";  
        // require_once "../app/Wechat/example/WxPay.AppPay.php";
        if($request){
            $money = $request['money'] ? $request['money'] : 1;
            if($money == ''){
                return ['code'=>'1002','message'=>'请传入充值金额'];
            }else{
                if(!$request->get('id')){
                    return ['code'=>'1003','message'=>'请传入用户信息'];
                }else{
                    $uid = $request->get('id') ? $request->get('id') : '';
                    // 获取用户信息
                    $user = Db::table('social_user')->where('id',$uid)->first();
                    $user = json_decode(json_encode($user),true);
                    // 微信预下单
                    $notify = new \AppPay();
                    /*首先生成prepayid*/
                    $input = new \WxPayUnifiedOrder();
                    $input->SetBody("账户余额充值");//商品或支付单简要描述(必须填写)
                    $input->SetOut_trade_no(\WxPayConfig::MCHID.date("YmdHis"));//订单号(必须填写)
                    $input->SetTotal_fee($money*100);//订单金额(必须填写)
                    $input->SetNotify_url("https://e.shidaichuxing.com/api/pay/wxpayNotify");//回调URL(必须填写)
                    $input->SetTrade_type("APP");//交易类型(必须填写)
                    // $input->SetProduct_id("1001");//rade_type=NATIVE，此参数必传。此id为二维码中包含的商品ID，商户自行定义。
                    $order = \WxPayApi::unifiedOrder($input);//获得订单的基本信息，包括prepayid
                    // dump($order);exit;
                    $appApiParameters = $notify->GetAppApiParameters($order);//生成提交给app的一些参数 
                    $list = $input->GetValues();
                    $list['timestamp'] = time();
                    // dump($list);exit;
                    
                    // 生成一条待付款的微信充值订单数据
                    $data['money'] = $money;
                    $data['source_id'] = $user['id'];
                    $data['source'] = 0;
                    $data['pay_way'] = 1;
                    $data['status'] = 1;
                    $data['out_trade_no'] = $list['out_trade_no'];
                    // 增加一条充值订单数据并返回订单ID
                    $add = Db::table('social_recharge_log')->insertGetId($data);
                    return ['code'=>'1000','message'=>'生成订单成功!','appApiParameters'=>json_decode($appApiParameters,true),'payorder'=>(string)$add,'out_trade_no'=>(string)$list['out_trade_no']];
                }
            }
        }else{
            return ['code'=>'1001','message'=>'获取数据失败，未接收到充值信息！'];
        }
    }
    // 手动查询订单情况
    public function orderselect(Request $request)
    {
        require_once "../app/Wechat/Autoloader.php"; 
        $input = new \WxPayOrderQuery();
        $out_trade_no = $request['out_trade_no'];
        $input->SetOut_trade_no($out_trade_no);
        // dump($out_trade_no);
        $list = \WxPayApi::orderQuery($input);
        // $res = json_decode($list);
        return $list;
    }
    // 个人充值订单状态查询/更改
    public function ordersave(Request $request){
        // $num = $request['num'];
        $num = $request['wxorder_num'] ? $request['wxorder_num'] : '';
        $data['status'] = 0;
        $data['created_at'] = date("Y-m-d H:i:s",time());
        $res = Db::table('social_recharge_log')->where('out_trade_no',$num)->update($data);
        $list = Db::table('social_recharge_log')->select('money','source_id')->where('out_trade_no',$num)->first();
        $list = json_decode(json_encode($list),true);
        // dump($list);
        $money = floatval($list['money']);
        // var_dump($money);die();
        $uid = $list['source_id'];
        $user = Db::table('social_user')->where('id',$list['source_id'])->increment('sum_money',$money);
        if($res && $user){
            return ['code'=>'1000','message'=>'充值成功!'];
        }else{
            return ['code'=>'1001','message'=>'充值失败!'];
        }
    }
    // 回调地址
    public function wxpayNotify(Request $Request) {
        ini_set('date.timezone', 'Asia/Shanghai');
        require_once "../app/Wechat/lib/WxPay.Api.php";  
        require_once "../app/Wechat/example/WxPay.AppPay.php";
        
        error_reporting(E_ERROR);
        //初始化日志
        $logHandler = new \CLogFileHandler("../logs/" . date('Y-m-d') . '.log');
        Log::Init($logHandler, 15);
        Log::DEBUG("begin notify");
        
        //在PayNotifyCallBack中重写了NotifyProcess，会发起一个订单支付状态查询，其实也可以不去查询，因为从php://input中已经可以获取到订单状态。file_get_contents("php://input")
        $notify = new \WxPayNotify();
        $notify = new \PayNotifyCallBack();
        // $list = file_get_contents("php://input");
        // $notify->Handle(false);
        $result = $notify->GetValues();
        // dump($list);
        $mes = [];
        if ($result['trade_state'] == 'SUCCESS') {
            $num = $request['out_trade_no'] ? $request['out_trade_no'] : '';
            $data['status'] = 0;
            $data['created_at'] = date("Y-m-d H:i:s",time());
            $res = Db::table('social_recharge_log')->where('out_trade_no',$num)->update($data);
            $list = Db::table('social_recharge_log')->select('money','source_id')->where('out_trade_no',$num)->first();
            $list = json_decode(json_encode($list),true);
            // dump($list);
            $money = $list['money'];
            $uid = $list['source_id'];
            $user = Db::table('social_user')->where('id',$list['source_id'])->increment('sum_money',$money);
            if($res && $user){
                return ['code'=>'1000','message'=>'充值成功!'];
            }else{
                return ['code'=>'1001','message'=>'充值失败!'];
            }
        }else{
            $mes =   [
                    'message'=> '参数错误',
                    'code'=>'1003',
                ];
        }
        return json_encode($mes);
        Log::DEBUG("end notify");
        Log::INFO(str_repeat("=", 20));
    }
    
}
